# coding: utf-8

# NOTE by zhouhl 2018-04-02
# 修复虚拟号使用次数脚本

import os
import set_env_path     # 请勿删除

from sqlalchemy import create_engine
from sqlalchemy.sql import text


engine = create_engine(
    os.getenv('DATABASE_URL')
    or 'mysql+pymysql://root:@127.0.0.1/wph_www_prod?charset=utf8'
)
conn = engine.connect()


def fix_virtual_number_use_count():
    query_virtual_number_sql = text("""
        select id, tel from number_pool_for_lt;
    """)

    get_valid_virtual_number_record_count_sql = text("""
        select count(*) as count from virtual_numbers where tel_x=:tel_x and valid=1;
    """)

    update_use_count_sql = text("""
        update number_pool_for_lt set use_count=:use_count where id=:id;
    """)

    virtual_numbers = conn.execute(
        query_virtual_number_sql
    ).fetchall()

    for i in virtual_numbers:
        use_count = conn.execute(
            get_valid_virtual_number_record_count_sql,
            tel_x=i.tel
        ).fetchone()
        conn.execute(
            update_use_count_sql,
            use_count=use_count.count,
            id=i.id,
        )


if __name__ == '__main__':
    fix_virtual_number_use_count()
